local REFRESH_HEADER_HEIGHT = 52.0
local STRING_FONT_SIZE 		= 12.0
-- NSTextAlignment
NSTextAlignmentCenter		= 1											-- Visually centered
M_PI					 	= 3.14159265358979323846264338327950288   	-- pi

waxClass{"PullRefreshTableViewController", UITableViewController,protocols={"UITableViewDelegate", "UITableViewDataSource"}}

function setupStrings(self)
	self.textPull		= "Pull down to refresh..."
	self.textRelease 	= "Release to refresh..."
	self.textLoading 	= "Loading..."
end

function init(self)
	self.super:init()
	self:setupStrings()
	return self
end

function initWithStyle(self,style)
  	self.super:initWithStyle(style)
	self:setupStrings()
  	return self
end



function viewDidLoad(self)
	self:tableView():setDataSource(self)
	self:addPullToRefreshHeader()
end

function addPullToRefreshHeader(self)
	local frame = UIScreen:mainScreen():bounds()
	self.refreshHeaderView = UIView:initWithFrame( CGRect( 0, 0 - REFRESH_HEADER_HEIGHT, frame.width, REFRESH_HEADER_HEIGHT))
	self.refreshHeaderView.backgroundColor = UIColor:clearColor()

	self.refreshLabel = UILabel:initWithFrame( CGRect( 0, 0, frame.width, REFRESH_HEADER_HEIGHT ) )
	self.refreshLabel:setBackgroundColor( UIColor:clearColor() )
	self.refreshLabel:setFont( UIFont:boldSystemFontOfSize( STRING_FONT_SIZE ) )
	self.refreshLabel:setTextAlignment( NSTextAlignmentCenter )

	self.refreshArrow = UIImageView:initWithImage(UIImage:imageNamed( "arrow.png" ) )
    self.refreshArrow:setFrame(CGRect(math.floor( ( REFRESH_HEADER_HEIGHT - 27 ) / 2 ),
									 math.floor( ( REFRESH_HEADER_HEIGHT - 44 ) / 2 ),
	 								 27,
									 44))

	self.refreshSpinner = UIActivityIndicatorView:initWithActivityIndicatorStyle(UIActivityIndicatorViewStyleGray)
	self.refreshSpinner:setFrame(CGRect(math.floor( math.floor( REFRESH_HEADER_HEIGHT - 20 ) / 2) ,
										math.floor( ( REFRESH_HEADER_HEIGHT - 20 ) / 2 ), 
										20, 
										20))
	self.refreshSpinner:setHidesWhenStopped( true )

	self.refreshHeaderView:addSubview( self.refreshLabel )
	self.refreshHeaderView:addSubview( self.refreshArrow )
	self.refreshHeaderView:addSubview( self.refreshSpinner )

	self:tableView():addSubview( self.refreshHeaderView )
end

function scrollViewWillBeginDragging(self, scrollView)
	if self.isLoading then
		return
	end
	self.isDragging = true;
end

function scrollViewDidScroll(self, scrollView)
	if self.isLoading then
		-- Update the content inset, good for section headers
		if scrollView:contentOffset().y > 0 then
            self:tableView():setContentInset(UIEdgeInsets( 0, 0, 0, 0 ))
		elseif scrollView:contentOffset().y >= -REFRESH_HEADER_HEIGHT then
            self:tableView():setContentInset(UIEdgeInsets(-scrollView:contentOffset().y, 0, 0, 0))
		end
	elseif self.isDragging and scrollView:contentOffset().y < 0 then
		-- Update the arrow direction and label
		local animation = function()
			if (scrollView:contentOffset().y < -REFRESH_HEADER_HEIGHT) then
				-- User is scrolling above the header
				self.refreshLabel:setText( self.textRelease )
				self.refreshArrow:layer():setTransform( LuaCATransform3D:CATransform3DMakeRotationAngle_x_y_z(M_PI, 0, 0, 1))
			else
				-- User is scrolling somewhere within the header
				self.refreshLabel:setText( self.textPull )
				self.refreshArrow:layer():setTransform( LuaCATransform3D:CATransform3DMakeRotationAngle_x_y_z(M_PI * 2, 0, 0, 1))
			
			end
		end
		UIView:beginAnimations_context(nil, nil) 
		UIView:setAnimationDuration(0.25) 
		animation()
		UIView:commitAnimations()
	end
end

function scrollViewDidEndDragging_willDecelerate(self, scrollView, decelerate)
	if (self.isLoading) then
		return
	end
	self.isDragging = false;
	if (scrollView:contentOffset().y <= -REFRESH_HEADER_HEIGHT) then
		-- Released above the header
		self:startLoading();
	end
end

function startLoading(self)
	self.isLoading = true;

	-- Show the header
	local animation = function()
        self:tableView():setContentInset( UIEdgeInsets( REFRESH_HEADER_HEIGHT, 0, 0, 0 ) )
		self.refreshLabel:setText( self.textLoading )
		self.refreshArrow:setHidden( true)
		self.refreshSpinner:startAnimating()
	end
	
	UIView:beginAnimations_context(nil, nil) 
	UIView:setAnimationDuration(0.3) 
	animation()
	UIView:commitAnimations()

	-- Refresh action!
	 self:refresh()
end

function stopLoading(self)
	self.isLoading = false;

	local stopAnimate = function()
		self:tableView():setContentInset(UIEdgeInsets( 0, 0, 0, 0 ))
		self.refreshArrow:layer():setTransform( LuaCATransform3D:CATransform3DMakeRotationAngle_x_y_z(M_PI * 2, 0, 0, 1) );
	end

	 -- Hide the header
	UIView:beginAnimations_context(nil, nil) 
	UIView:setAnimationDelegate(self)
	UIView:setAnimationDidStopSelector("stopAnimateEnd")
	UIView:setAnimationDuration(0.3)

	stopAnimate()

	UIView:commitAnimations()
end

function stopLoadingComplete(self)
	 -- Reset the header
	 self.refreshLabel:setText(self.textPull)
	 self.refreshArrow:setHidden(false)
	 self.refreshSpinner:stopAnimating()
end

function refresh(self)
	 -- This is just a demo. Override this method with your custom reload action.
	 -- Don't forget to call stopLoading at the end.
	self:performSelector_withObject_afterDelay("stopLoading", nil, 2.0)
end

function stopAnimateEnd(self)
	self:performSelector("stopLoadingComplete");
end

-- DataSource
-------------
function numberOfSectionsInTableView(self, tableView)
  return 2
end

function tableView_numberOfRowsInSection(self, tableView, section)
  return 5
end

function tableView_cellForRowAtIndexPath(self, tableView, indexPath)  
  local identifier = "CapitalsTableCell"
  local cell = tableView:dequeueReusableCellWithIdentifier(identifier) or
			   UITableViewCell:initWithStyle_reuseIdentifier(UITableViewCellStyleValue1, identifier)  

  --local key = table.keys(self.state)[indexPath:row() + 1]
  cell:detailTextLabel():setText(tostring(indexPath:row()))
  cell:textLabel():setText(tostring(indexPath:row()))
  cell:setSelectionStyle(UITableViewCellSelectionStyleNone)

  return cell
end



